﻿using System.Collections.Generic;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using SdmxMl.Helper;
using SdmxMl.Common;

namespace SdmxMl.Structure
{
    /// <summary>
    /// TransitionType describes the Condition and next step in a transition.
    /// The Condition text is informational, and may be supplied in multiple,
    /// parallel-language form. The TargetStep holds the id of the next step
    /// in the process if the condition is met.
    /// </summary>
    public class TransitionType 
    {
        #region Properties

        private MultiLang _condition;
        public MultiLang Condition
        {
            get { return _condition; }
        }

        private string _targetStep;
        public string TargetStep
        {
            get { return _targetStep; }
            set { _targetStep = value; }
        }

        #endregion

        #region Constructors

        private void Init()
        {
             _condition = new MultiLang();
       }

        public TransitionType()
        {
            Init();
        }


        public TransitionType(XmlNode nodeArtefact, XmlNamespaceManager nsmgr)
        {
            Init();
            _targetStep = Xmlhelper.GetNodeText(nodeArtefact, "./structure:TargetStep", nsmgr);

            _targetStep = _targetStep.Replace(".", "_");

            MultiLangNodeReader mr = new MultiLangNodeReader();
            mr.Read(_condition, nodeArtefact, "Condition", nsmgr, false);
        }

        #endregion

        #region XML serialize

        public void WriteXml(XmlTextWriter xw, string prefix, string tag)
        {
            // Something defined ?
            if (string.IsNullOrEmpty(_targetStep) == false &&
                _condition.IsEmpty == false)
            {
                xw.WriteStartElement(prefix, tag, null);

                Xmlhelper.WriteElementIfExist(xw, prefix, "TargetStep", _targetStep);
                _condition.WriteXml(xw, prefix, "Condition");

                xw.WriteEndElement();
            }
        }

        #endregion //XML serialize

    }


    public class TransitionTypeList : List<TransitionType>
    {
        /// <summary>Presents transitions as datatable</summary>
        /// <returns>a datatable representation</returns>
        public DataTable AsDataTable()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(new DataColumn("Step", typeof(string)));
            dataTable.Columns.Add(new DataColumn("Cond", typeof(string)));

            foreach (TransitionType tr in this)
                dataTable.Rows.Add(new object[] { tr.TargetStep, tr.Condition.ToString() });

            return dataTable;
        }
    }
}
